package pe.edu.upc.groupon.controller;

import java.lang.reflect.Type;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import pe.edu.upc.groupon.model.Deal;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
public class DealControllerWeb {

	@Autowired
	private RestTemplate restTemplate;
	
	private Gson gson = new Gson();
	
	@RequestMapping("/deal.htm")
	public String getDeal(Model model, @RequestParam("id") String id)
	{
		String response = restTemplate.getForObject("http://localhost:8080/groupon_bill_gates_final/services/deals/{id}",
				String.class, id);
		
		Deal deal = gson.fromJson(response, Deal.class);
		
		model.addAttribute("deal", deal);
		
		return "deal";
	}
	
	@RequestMapping("/deals.htm")
	public String getDeals(Model model)
	{
		String response = restTemplate.getForObject("http://localhost:8080/groupon_bill_gates_final/services/deals/",
				String.class);
		
		List<Deal> deals = gson.fromJson(response, getGsonType());
		model.addAttribute("deals",deals);
		
		return "deals";
	}
	
	@RequestMapping("/dealqueue.htm")
	public String sendMessage()
	{
		ResponseEntity<String> responsejms = restTemplate.postForEntity("http://localhost:8080/groupon_bill_gates_final/services/deals", "JC", String.class);
		return "redirect:deals.htm";
	}
	
	private Type getGsonType()
	{
		return new TypeToken<List<Deal>>(){
		}.getType();
	}
}
